<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Many to Many - Join Table</title>
</head>
<body>
  <h3>Many to Many - Join Table</h3>
  Many to Many relationship has to be mapped using a join table. Taking an example, let's say we are mapping
  blog posts and tags to be associated with them. A post can have multiple tags associated with it and same holds
  true for tags too, making this association a many-to-many association. Let's consider unidirectional association
  first. A post doesn't know about the tags associated with it but a tag knows
  about the posts. Therefore, Tag maintains collection of posts and marks it with <em>@ManyToMany</em> and
  <em>@JoinTable</em> annotations as shown below -
  <pre class="brush: java">
@ManyToMany
@JoinTable(name = "mtm_bidi_post_tag",
  joinColumns = @JoinColumn(name = "tag_id"),
  inverseJoinColumns = @JoinColumn(name = "post_id")
)
public Set&lt;Post&gt; getPosts() {
	return posts;
}
  </pre>
  The join table maintains two foreign keys, one to table of Post entity and the other to table of
  Tag entity. The names of the columns are provided using <em>@JoinColumn</em>  annotation. The <em>joinColumns</em>
  attribute of the <em>@JoinTable</em> annotation refers to the primary key of the owning entity i.e. Tag in this
  example, while the <em>inverseJoinColumns</em> attribute refers to primary key of inverse side i.e. Post entity.
  The primary key for the join table is composite key made up of the two foreign keys.
  
  <h4>Making the association bidirectional</h4>
  This association can be made bidirectional by maintaining a collection of Tags in Post entity. It is also marked with
  <em>@ManyToMany</em> annotation but with a <em>mappedBy</em> attribute to indicate it's the inverse side in the
  relationship.
  <pre class="brush: java">
@ManyToMany(mappedBy = "posts")
public Set&lt;Tag&gt; getTags() {
  return tags;
}
  </pre>
</body>
</html>
